import { useState } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Search, Trophy, Calendar } from "lucide-react"
import { LeagueSearchResult } from '@/types/dota'
import { openDotaAPI } from '@/services/api'

interface LeagueSearchProps {
  onLeagueSelect: (league: LeagueSearchResult) => void
}

function LeagueSearch({ onLeagueSelect }: LeagueSearchProps) {
  const [searchQuery, setSearchQuery] = useState('')
  const [searchResults, setSearchResults] = useState<LeagueSearchResult[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleSearch = async () => {
    if (!searchQuery.trim()) {
      setError('请输入联赛名称或ID')
      return
    }

    setLoading(true)
    setError(null)

    try {
      const results = await openDotaAPI.searchLeagues(searchQuery.trim())
      console.log('搜索结果:', results)
      results.forEach(league => {
        console.log(`联赛 ${league.name}:`, {
          start_time: league.start_time,
          start_time_formatted: league.start_time ? formatDate(league.start_time) : '未知',
          start_time_date: league.start_time ? new Date(league.start_time * 1000) : null
        })
      })
      setSearchResults(results)
      
      if (results.length === 0) {
        setError('未找到匹配的联赛')
      }
    } catch (err) {
      setError('搜索联赛失败，请稍后重试')
      console.error('League search error:', err)
    } finally {
      setLoading(false)
    }
  }

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSearch()
    }
  }

  const formatDate = (timestamp?: number) => {
    if (!timestamp) return '未知'
    
    // 添加调试日志
    console.log('formatDate 调用:', {
      输入timestamp: timestamp,
      转换后日期: new Date(timestamp * 1000),
      格式化结果: new Date(timestamp * 1000).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long', 
        day: 'numeric'
      })
    })
    
    return new Date(timestamp * 1000).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    })
  }

  // const formatPrizePool = (amount?: number) => {
  //   if (!amount) return '未知'
  //   return `$${amount.toLocaleString()}`
  // }

  const getTierColor = (tier: string) => {
    switch (tier.toLowerCase()) {
      case 'premium': return 'bg-yellow-500'
      case 'professional': return 'bg-blue-500'
      case 'amateur': return 'bg-green-500'
      default: return 'bg-gray-500'
    }
  }

  return (
    <div className="space-y-6">
      {/* 搜索区域 */}
      <Card className="modern-card">
        <CardHeader>
          <CardTitle className="text-2xl font-bold text-foreground flex items-center space-x-2">
            <Trophy className="h-6 w-6" />
            <span>联赛数据</span>
          </CardTitle>
          <CardDescription className="text-muted-foreground">
            搜索联赛名称或联赛ID来查找联赛信息和比赛数据
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex space-x-2">
            <Input
              type="text"
              placeholder="输入联赛名称或ID (例如: The International, 65006)"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              onKeyPress={handleKeyPress}
              className="flex-1"
            />
            <Button 
              onClick={handleSearch}
              disabled={loading}
              className="modern-button-primary"
            >
              <Search className="h-4 w-4 mr-2" />
              {loading ? '搜索中...' : '搜索'}
            </Button>
          </div>
          
          {error && (
            <div className="mt-4 p-3 bg-destructive/10 border border-destructive/20 rounded-lg">
              <div className="text-sm text-destructive">{error}</div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 搜索结果 */}
      {searchResults.length > 0 && (
        <Card className="modern-card">
          <CardHeader>
            <CardTitle className="text-xl font-bold text-foreground">
              搜索结果 ({searchResults.length})
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {searchResults.map((league) => (
                <div
                  key={league.leagueid}
                  className="p-4 border border-border rounded-lg hover:bg-muted/50 transition-colors cursor-pointer"
                  onClick={() => onLeagueSelect(league)}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center space-x-3 mb-2">
                        <h3 className="text-lg font-semibold text-foreground">
                          {league.name}
                        </h3>
                        <Badge className={`${getTierColor(league.tier)} text-white`}>
                          {league.tier}
                        </Badge>
                      </div>
                      
                      <div className="text-sm text-muted-foreground mb-2">
                        联赛ID: {league.leagueid}
                      </div>
                      
                      <div className="flex items-center space-x-4 text-sm text-muted-foreground">
                        {league.start_time && (
                          <div className="flex items-center space-x-1">
                            <Calendar className="h-4 w-4" />
                            <span>开始: {formatDate(league.start_time)}</span>
                          </div>
                        )}
                        
                        {/* {league.prize_pool && (
                          <div className="flex items-center space-x-1">
                            <DollarSign className="h-4 w-4" />
                            <span>奖金池: {league.prize_pool}</span>
                          </div>
                        )} */}
                        
                        {league.region && (
                          <div className="text-muted-foreground">
                            地区: {league.region}
                          </div>
                        )}
                      </div>
                    </div>
                    
                    <Button variant="outline" size="sm">
                      查看详情
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* 加载状态 */}
      {loading && (
        <Card className="modern-card">
          <CardContent>
            <div className="flex items-center justify-center py-12">
              <div className="flex items-center space-x-3">
                <div className="loading-spinner w-6 h-6"></div>
                <span className="text-muted-foreground">正在搜索联赛...</span>
              </div>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}

export default LeagueSearch